﻿using OpenVision.Data;
using OpenVision.Models;
using OpenVision.Repositories;
using OpenVisionWebService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace OpenVisionWebService.Controllers
{
    [EnableCors(origins: "http://dogdream.apphb.com", headers: "*", methods: "*")]
    public class CollarController : BaseController
    {
        private readonly ICollarRepository data;

        public CollarController()
        {
            this.data = new DbCollarsRepository(new OpenVisionContext());
        }

        public CollarController(ICollarRepository repository)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("Invalid repository! It cannot be null!");
            }

            this.data = repository;
        }

        [HttpPut]
        [ActionName("position")]
        public HttpResponseMessage UpdatePosition([FromBody]
                                                  CollarPositionModel model)
        {
            return base.PerformOperationAndHandleExceptions(() =>
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Invalid collar model!");
                }

                this.data.UpdatePosition(model.Longitude, model.Latitude, model.Id);

                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                return response;
            });
        }

        [HttpGet]
        public HttpResponseMessage GetCollar(string sessionKey)
        {
            return base.PerformOperationAndHandleExceptions(() =>
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Invalid collar model!");
                }

                Collar collar = this.data.GetPosition(sessionKey);

                CollarGetPositionModel collarModel = CollarGetPositionModel.CreateModel(collar);

                var response = this.Request.CreateResponse<CollarGetPositionModel>(HttpStatusCode.OK, collarModel);
                return response;
            });
        }

        [HttpGet]
        [ActionName("changes")]
        public HttpResponseMessage CheckForChanges(int id)
        {
            return base.PerformOperationAndHandleExceptions(() =>
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Invalid collar model!");
                }

                ChangesUpdates changesModel = this.data.CheckForChanges(id);

                var response = this.Request.CreateResponse<ChangesUpdates>(HttpStatusCode.OK, changesModel);
                return response;
            });
        }
    }
}